<?php

namespace App\Filament\Resources;

use App\Models\Post;
use BackedEnum;
use Filament\Forms;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Actions\Action;
use Filament\Actions\BulkAction;
use Filament\Actions\EditAction;
use Filament\Actions\ViewAction;
use Illuminate\Database\Eloquent\Builder;

class PostReviewResource extends Resource
{
    protected static ?string $model = Post::class;

    protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedCheckCircle;

    protected static ?string $navigationLabel = '文章审核';

    protected static ?string $modelLabel = '待审核文章';

    protected static ?string $pluralModelLabel = '待审核文章';

    protected static ?int $navigationSort = 5;

    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::where('is_approved', false)
            ->where('status', 'published')
            ->count();
    }

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Forms\Components\TextInput::make('title')
                    ->label('标题')
                    ->disabled()
                    ->columnSpan(2),
                Forms\Components\TextInput::make('user.name')
                    ->label('作者')
                    ->disabled(),
                Forms\Components\DateTimePicker::make('created_at')
                    ->label('提交时间')
                    ->disabled(),
                Forms\Components\Select::make('access_level')
                    ->label('访问权限')
                    ->options([
                        'public' => '公开',
                        'login_required' => '需要登录',
                        'followers_only' => '仅关注者',
                        'private' => '私密',
                    ])
                    ->disabled(),
                Forms\Components\Select::make('status')
                    ->label('状态')
                    ->options([
                        'draft' => '草稿',
                        'published' => '已发布',
                        'scheduled' => '定时发布',
                        'archived' => '已归档',
                    ])
                    ->disabled(),
                Forms\Components\Textarea::make('excerpt')
                    ->label('摘要')
                    ->disabled()
                    ->rows(3)
                    ->columnSpanFull(),
                Forms\Components\Textarea::make('content')
                    ->label('内容')
                    ->disabled()
                    ->rows(10)
                    ->columnSpanFull(),
                Forms\Components\Toggle::make('is_approved')
                    ->label('批准发布')
                    ->helperText('选中后文章将公开显示'),
                Forms\Components\Textarea::make('rejected_reason')
                    ->label('拒绝原因')
                    ->placeholder('如果拒绝，请说明原因')
                    ->rows(3)
                    ->columnSpanFull(),
            ])
            ->columns(2);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('title')
                    ->label('标题')
                    ->searchable()
                    ->limit(50),
                Tables\Columns\TextColumn::make('user.name')
                    ->label('作者')
                    ->searchable(),
                Tables\Columns\TextColumn::make('status')
                    ->label('状态')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'draft' => 'danger',
                        'pending' => 'warning',
                        'published' => 'success',
                        default => 'gray',
                    })
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'draft' => '草稿',
                        'pending' => '待审核',
                        'published' => '已发布',
                        default => $state,
                    }),
                Tables\Columns\IconColumn::make('is_approved')
                    ->label('审核状态')
                    ->boolean()
                    ->trueIcon('heroicon-o-check-circle')
                    ->falseIcon('heroicon-o-x-circle')
                    ->trueColor('success')
                    ->falseColor('danger'),
                Tables\Columns\TextColumn::make('access_level')
                    ->label('访问权限')
                    ->badge()
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'public' => '公开',
                        'login_required' => '需登录',
                        'followers_only' => '仅关注者',
                        'private' => '私密',
                        default => $state,
                    }),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('提交时间')
                    ->dateTime()
                    ->sortable(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('is_approved')
                    ->label('审核状态')
                    ->options([
                        '0' => '未审核',
                        '1' => '已审核',
                    ]),
                Tables\Filters\SelectFilter::make('access_level')
                    ->label('访问权限')
                    ->options([
                        'public' => '公开',
                        'login_required' => '需要登录',
                        'followers_only' => '仅关注者',
                        'private' => '私密',
                    ]),
            ])
            ->actions([
                Action::make('approve')
                    ->label('批准')
                    ->icon('heroicon-o-check')
                    ->color('success')
                    ->requiresConfirmation()
                    ->action(function (Post $record) {
                        $record->update([
                            'is_approved' => true,
                            'approved_at' => now(),
                            'approved_by' => auth()->id(),
                        ]);
                    })
                    ->visible(fn (Post $record) => !$record->is_approved),

                Action::make('reject')
                    ->label('拒绝')
                    ->icon('heroicon-o-x-mark')
                    ->color('danger')
                    ->requiresConfirmation()
                    ->form([
                        Forms\Components\Textarea::make('rejected_reason')
                            ->label('拒绝原因')
                            ->required()
                            ->rows(3),
                    ])
                    ->action(function (Post $record, array $data) {
                        $record->update([
                            'is_approved' => false,
                            'rejected_reason' => $data['rejected_reason'],
                            'status' => 'draft',
                        ]);
                    })
                    ->visible(fn (Post $record) => !$record->is_approved),

                ViewAction::make()
                    ->label('查看'),
                EditAction::make()
                    ->label('编辑'),
            ])
            ->bulkActions([
                BulkAction::make('approve_bulk')
                    ->label('批量批准')
                    ->icon('heroicon-o-check')
                    ->color('success')
                    ->requiresConfirmation()
                    ->action(function ($records) {
                        $records->each(function ($record) {
                            $record->update([
                                'is_approved' => true,
                                'approved_at' => now(),
                                'approved_by' => auth()->id(),
                            ]);
                        });
                    }),
            ])
            ->defaultSort('created_at', 'desc');
    }

    public static function getRelations(): array
    {
        return [];
    }

    public static function getPages(): array
    {
        return [
            'index' => \App\Filament\Resources\PostReviewResource\Pages\ListPostReviews::route('/'),
            'edit' => \App\Filament\Resources\PostReviewResource\Pages\EditPostReview::route('/{record}/edit'),
        ];
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->where('status', 'published')
            ->where('is_approved', false);
    }

    public static function getNavigationGroup(): ?string
    {
        return '内容管理';
    }
}